﻿
$(document).ready(function () {       

    //$(".widget-box-right").find('.contact-list').append('<img src="../../img/wait.gif" alt="wait" id="wait" style="display: block; margin: auto auto; margin-top: 110px;"/>');

    chatHub = $.connection.chatHub;


    $('.closesend').click(function () {
        $('.widget-chat').css('display', 'none');
    });
    $('.user').click(function () {

        $('.widget-chat').css('display', 'block');
    });

    audio = $("#mysoundclip")[0];


    $('#send-msg-all').click(function () {
        OpenPrivateChatWindow(chatHub, "HV-1", "HV-1", "Thông báo chung", true,'');
    })

    chatHub.client.reConnected = function () {
        //alert('Ket noi lai');
    }

    // Hien thi tin nhan Public
    chatHub.client.messageReceivedAll = function (toUserId, UserName,img, message, thoiGianGui, isPlay, isPublic) {
        //alert("Private\n" + "toUserId: " + toUserId + "\n" + "UserName: " + UserName + "\n" + "message: " + message + "\n" + "isPublic: " + isPublic + "\n")
        // Tao cua so chat            
        if (isPublic) {
            tenDN = "HV-1";
        }

        if ($('.' + toUserId).length < 1) {
            createPrivateChatWindow(chatHub, toUserId, tenDN, UserName, isPublic);
        }

        DisplayMessage(toUserId, tenDN,img, UserName, message, thoiGianGui, isPlay, false, isPublic);
    }

    // Hien thi tin nhan cu
    chatHub.client.messageReceived = function (response, idConnect, tenDN, isScroll) {

        //alert("Private\n" + "response: " + response + "\n" + "idConnect: " + idConnect + "\n" + "tenDN: " + tenDN + "\n" + "isScroll: " + isScroll + "\n")
        // alert(response)
        var xmlDoc = $.parseXML(response);
        var xml = $(xmlDoc);
        var rows = xml.find("Row");
        var thoigiangui;
        var lastTimes, lastTime = '';

        $.each(rows, function (index) {
            var row = $(this);
            thoigiangui = row.find("ThoiGianGui").text();
            thoigiangui = thoigiangui.substr(0, thoigiangui.indexOf('.'))
            lastTimes = thoigiangui.split(' ')

            DisplayMessage(idConnect, tenDN, row.find("Anh").text() == "" ? "avatar-default.jpg" : row.find("Anh").text(), row.find("TenNguoiGui").text(), row.find("NoiDung").text(), lastTimes[1], false, isScroll, false);

            if (lastTime != lastTimes[0] && index + 1 == rows.size()) {
                lastTime = lastTimes[0]
                $('.' + tenDN).find('#chat-messages-inner').prepend("<div class='date_spend_small'>" + lastTime + "</div>");
            }

            if (rows.size() == index + 1)
                $('.' + tenDN).attr('data-lasttime', row.find("ThoiGianGui").text())

        });

        if (rows.size() == 0)
            $('.' + tenDN).attr('data-lasttime', '')
        else {
            if (isScroll) {
                SetScroll(tenDN, 3)
            }
            else
                SetScroll(tenDN, 1)
        }

        $('.' + tenDN).find('#chat-messages').scroll(function () {
            if ($(this).scrollTop() == 0) {
                if ($('.' + tenDN).attr('data-lasttime') == '') return
                chatHub.server.loadMessage(TenDN, tenDN, idConnect, true, $('.' + tenDN).attr('data-lasttime'));
            }
        });

        $('.' + tenDN).find('#wait').remove();
    }

    // Hien thi danh sach Nguoi dung online
    chatHub.client.onConnected = function (ConnectedUsers) {
        // Add All Users    
        
        for (i = 0; i < ConnectedUsers.length; i++) {

            online = '<span class="icon" style="float: right">' +
                '<img src="../../img/online.png" alt="img" style="width: auto; height: auto;' +
                'margin-left: 15px;" class="online"/> </span>';

            $('#' + ConnectedUsers[i].TenDN).attr('data-id', ConnectedUsers[i].ConnectionId);
            $('#' + ConnectedUsers[i].TenDN).find('a').append(online);
        }

        //AddUser(chatHub, ConnectedUsers[i].ConnectionId, ConnectedUsers[i].MaHV,ConnectedUsers[i].Image, ConnectedUsers[i].UserName, false);
        //$('#wait').remove();
    }

    chatHub.client.thongBao = function (str) {
        alert(str);
    }


    // Dinh nghia ham gui msg
    chatHub.client.sendMessage = function (windowId, tenDN,img, fromUserName, message, thoiGianGui, isPlay, isPublic) {

        img == "" ? "avatar-default.jpg" : img;
        //alert("idConnect: " + windowId + "\n" + "tenDN: " + tenDN + "\n" + "fromUserName: " + fromUserName + "msg: " + message + "\n" + "isPublic: " + isPublic + "\nisPlay: " + isPlay + "\n")
        // Tim window chat
        if ($('.' + tenDN).length == 0)
            createPrivateChatWindow(chatHub, windowId, tenDN, fromUserName, isPublic)

        // Hien thi Message
        DisplayMessage(windowId, tenDN, img, fromUserName, message, thoiGianGui, isPlay, false, isPublic);
        SetScroll(tenDN,1)
    }

    // khi co nguoi dung moi online
    chatHub.client.onNewUserConnected = function (idConnect, tenDN /*, name, image*/) {

        //alert("Online: " + tenDN + " - idConnect: " + idConnect);

        var $item = $('#' + tenDN);

        // Neu ton tai nguoi dung tren danh sach online
        if ($item.length > 0) {

            $item.find(':nth-child(1)').find('.online').remove();

            // them idConnect khi user online
            $item.attr('data-id', idConnect);

            $item.find(':nth-child(1)').append('<img class="online" src="../../img/online.png" alt="Alternate Text" style="width: auto; height: auto;' +
                'margin-left: 15px;" />');

            // Neu cua so chat dang mo thi them idConnect moi vao
        }
        if ($('.' + tenDN).length > 0)
            $('.' + tenDN).attr('id', idConnect)
        //else
        //    AddUser(chatHub, idConnect, tenDN, name, image, false);     // Them moi vao danh sach online
    }

    // Khi nguoi dung tat cua so trinh duyet thi la thoat 
    chatHub.client.onUserDisconnected = function (tenDN) {
        // Xoa IdConnect tren cua so chat neu bat

      //  alert("user con lai: " + listuser.length);

        $('.' + tenDN).attr('id', '')
        $('.' + tenDN).find('.icon:first').find(':nth-child(1)').remove();
        $('.' + tenDN).find('.icon:first').append('<i class="icon-comment"></i>');
        // Bo danh dau online
        $(".widget-box-right").find('.contact-list').find('#' + tenDN).attr('data-id', '').find(':nth-child(1)').find(':nth-child(3)').remove();
    }


    $.connection.hub.start().done(function () {            
        // Gui thong tin nguoi dung len server
                   
        chatHub.server.connect(TenDN, TenNguoiDung, Anh);

        $('#contact-list').find('li').click(function () {
            OpenPrivateChatWindow(chatHub, $(this).attr('data-id') == undefined ? "" : $(this).attr('data-id'), $(this).attr('id'), $(this).find('.name-user').html(), false,'');
        })
    });    
});

function SetScroll(TenDN, DivNumber) {
    var height;
    height = $('.' + TenDN).find('#chat-messages')[0].scrollHeight;

    $('.' + TenDN).find('.chat-messages').scrollTop(height / DivNumber);
}

function DisplayMessage(windowId, tenDN, img, fromUserName, message, thoiGianGui, play, isScroll, isPublic) {

    //alert("DisplayMessage\n" + "windowId: " + windowId + "\n" + "tenDN: " + tenDN + "\n" + "fromUserName: " + fromUserName + "\n" + "play: " + play + "\n" + "isScroll: " + isScroll + "\n" + "isPublic: " + isPublic + "\n")

    var messages = '<p style="display: block;" class="box-msg"><span class="msg-block">  ' +
                  '<img src="../uploads/avatar/' + img + '" alt=""><strong>' + fromUserName + '</strong> <span class="time">' + thoiGianGui + '</span><span ' +
                  'class="msg">' + message + '</span></span></p>'
    if(isScroll)
        $('.' + tenDN).find('#chat-messages-inner').prepend(messages);
    else
        $('.' + tenDN).find('#chat-messages-inner').append(messages);

    if (play)
        audio.play();
}

function OpenDialog(obj) {
    $(obj).parent().find('.File').click();
}

function UploadFile(obj) {

    // Kiem tra co ket noi internet ko
    if (!navigator.onLine) {
        alert("Không có kết nối mạng.\nHãy kiểm tra lại kết nối của bạn")
        return;
    }
    // Lay id de gui
    var idConnect = $(obj).parent().parent().parent().parent().attr('id')
    var classs = $(obj).parent().parent().parent().parent().attr('class').split(' ');
    var tenDN = classs[classs.length - 1];

    idConnect = idConnect === undefined ? "" : idConnect;

    //alert("-" + idConnect + "-" + tenDN);

    var isPublic = false;

    if (idConnect == "HV-1")
        isPublic = true;

    var files = $(obj).parent().find('.File').get(0).files;

    if (files.length == 0) {
        //alert("Khong file nao duoc chon.");
        return;
    }

    var formData = new FormData();
    var error = false;

    for (var i = 0; i < files.length; i++) {
        // Upload file < 25Mb
        if (files[i].size / 1024 <= 25600 && files[i].name.length <= 200)
            formData.append(files[i].name, files[i]);
        else
            error = true;
    }

    if (error)
        alert("Một số file không được tải lên!\nDung lượng file phải nhỏ hơn 25Mb \nvà tên file không dài quá 200 ký tự")

    $.ajax(
    {
        ///server script to process data
        url: "../Upload.ashx", //web service
        type: 'POST',
        complete: function () {
            $(obj).parent().find('.attach').attr('src', '../../img/file.png');
        },
        progress: function (evt) {
            //progress event    
        },
        ///Ajax events
        beforeSend: function (e) {
            $(obj).parent().find('.attach').attr('src', '../../img/wait.gif');
        },
        success: function (data) {
            //alert(e.d);
            var allowed_files = new Array(".jpg", ".png", ".gif");
            var file_extension, index, filename, message;
            $.each(data, function (key, val) {

                // Lay phan mo rog cua file
                file_extension = val.split('.').pop();

                // Cat ten file
                index = val.lastIndexOf('¿');
                filename = val.substr(index + 1, val.length - index)
                message = "";
                // Kiem tra file la kieu j
                for (var i = 0; i < allowed_files.length; i++)
                    if (file_extension == allowed_files[i])
                        message = '<img src="../../Uploads/Files/' + val + '" alt="Alternate Text" class="img-responsive"/>';

                if (message == "")
                    message = '<img src="../../img/files.png" style="width:16px; height:16px"/><a href="../Download.ashx?file=' + val + '" style="color:#fa8a40">' + filename + '</a>';

                // MaHV la ma friend
                // Kiem tra co fai send Public                      
                chatHub.server.sendMessage(idConnect, tenDN, message, isPublic, false);

            });
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        },
        ///Form data
        data: formData,
        ///Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });
}

// Mo cua so chat
function OpenPrivateChatWindow(chatHub, toUser, tenDN, userName, isPublic,lastTime) {
    // Neu ton tai cua so chat thi thoat
    if (isPublic && QuyenDN.length<1) return;
    if ($('.' + tenDN).length > 0) return;
        
    // Tao cua so chat
    createPrivateChatWindow(chatHub, toUser, tenDN, userName, isPublic);

    $('<img src="../../img/wait.gif" alt="wait" id="wait" style="display: block; margin: auto auto;"/>').insertAfter($('.' + tenDN).find('.widget-title'));
   
    if (navigator.onLine)      // Kiem tra co ket noi internet ko
    {
        chatHub.server.loadMessage(TenDN, tenDN, toUser, true, '');
    }
    else
        $('.' + tenDN).find('#wait').remove();
}

// Tao cua so chat
function createPrivateChatWindow(chatHub, idConnect, tenDN, name, isPublic) {

    if (isPublic) {
        tenDN = "HV-1";
        name = "Thông báo chung";
        idConnect = "HV-1";
    }

    var online = '<i class="icon-comment"></i>';

    if (idConnect != "")
        online = '<img src="../../img/online.png" alt="img"/>'

    divChat = ' <div class="widget-chat span3 widget-chat-small ' + tenDN + '" id="' + idConnect + '" data-lasttime="">' +
 '<div class="widget-box  widget-box-right">' +
  '   <div class="widget-title">' +
 '      <span class="icon"> ' + online + ' </span> ' +
 '        <h5>' + name + '</h5>        ' +
 '        <span class="icon" style="float: right">   ' +
 '            <img src="../../img/setting.png" alt="Alternate Text" style="margin-top: -6px;" class="setting"/>' +

 '            <img src="../../img/close.png" alt="Alternate Text" style="margin-top: -6px;" class="closesend" />' +
 '       </span> ' +
 '     </div> ' +
 '          <div class="hide" id="setting"><input id="check-message" type="checkbox" /><span> Gửi cho mọi người.</span></div> ' +
 '    <div class="chat-users panel-right2">  ' +
 '        <div class="chat-messages" id="chat-messages">      ' +
 '           <div id="chat-messages-inner">        ' +
 '      </div>  ' +
 '  </div>' +
 ' <div class="chat-message">  ' +
 '    <input class="File" type="file" onchange="UploadFile(this)" multiple="multiple"/>' +
 '   <span class="input-box">            ' +
        //'<input id="Button1" type="button" value="button"  />' +
 '       <input name="msg-box" id="msg-box" type="text">  ' +
 '   </span>   ' +
 '<span class="icon" onclick="OpenDialog(this)"><img src="../../img/file.png" alt="img" class="attach"/></span>' +
 //'    <a href=# class="btn btn-success" >Send</a> ' +
 '  </div> ' +
 ' </div>     ' +
 '</div>        ' +
' </div>';

    var $div = $(divChat);

    // DELETE BUTTON IMAGE
    $div.find('.closesend').click(function () {
        $('.' + tenDN).remove();

        var len = $('.widget-chat-small').length;

        $('.widget-chat-small').each(function (index) {

            var margin = (len - index - 1) * 280 + 10;
            $(this).css('right', margin);
        });

    });

    // Send event            
    $div.find("#msg-box").keypress(function (e) {
        // Neu lon hon 500 ky tu ko cho nhap nua
        if ($(this).val().length >= 500) {
            e.preventDefault();
        };

        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {

            e.preventDefault();       // Ko cho thao tac nua
            var msg = $(this).val();
            if (msg.length > 0) {
                // idConnect luon thay doi vi vay lay lai truoc khi truyen
                var idConnect = $div.attr('id');
                // Neu idConnect ko dinh nghia thi user dang offline
                idConnect = idConnect === undefined ? "" : idConnect;

                if (!navigator.onLine) {
                    alert("Không có kết nối mạng.\nHãy kiểm tra lại kết nối của bạn")
                    return;
                }
                chatHub.server.sendMessage(idConnect, tenDN, msg, isPublic, true);
                $(this).val('').focus();
            };
        }
    });

    $div.find(".setting").click(function () {
        $(this).parent().parent().parent().find('.chat-users').toggleClass('hide');
    })

    $('form').prepend($div);

    // Dinh vi tri cho cua so chat
    var countDivChat = $('.widget-chat-small').length;

    if (countDivChat > 4) countDivChat = 4;

    var margin = (countDivChat - 1) * 280 + 10;
    $('.' + tenDN).css('right', margin);
    $('.' + tenDN).find('#msg-box').focus();
}
